package com.flute.tools.timer;

public abstract class IntervalExecutor {
	private int interval;
	private boolean finish;
	private boolean daemMode;
	private String name;

	public IntervalExecutor() {
		this.interval = 1000;
		this.finish = false;
		this.daemMode = true;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	public int getInterval() {
		return this.interval;
	}

	public void stop() {
		this.finish = true;
	}

	public abstract void execute();

	public void start() {
		Thread thread = new Thread(getRunnable());
		if (name == null) {
			name = String.valueOf(thread.getId());
		}
		thread.setName(name);
		thread.setDaemon(daemMode);
		thread.start();
	}

	private Runnable getRunnable() {
		return new Runnable() {
			@Override
			public void run() {
				while (!finish) {
					execute();
					try {
						Thread.sleep(interval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
	}

	public boolean isDaemMode() {
		return daemMode;
	}

	public void setDaemMode(boolean daemMode) {
		this.daemMode = daemMode;
	}

	public void setFinish(boolean finish) {
		this.finish = finish;
	}
}
